package com.example.huadu_server.admin.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.example.huadu_server.admin.entity.Admin;
import com.example.huadu_server.admin.mapper.AdminMapper;
import com.example.huadu_server.admin.service.AdminAuthService;
import com.example.huadu_server.config.Response;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class AdminAuthServiceImpl implements AdminAuthService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AdminMapper adminMapper;

    private static final String REDIS_KEY_PREFIX = "REGISTER_CODE_";

     /*
         登录
     */

    @Autowired
    private Producer kaptchaProducer;

    /**
     * 生成登录验证码
     */
    @Override
    public void generateLoginCode(HttpServletResponse response) {
        // 生成验证码
        String captchaText = kaptchaProducer.createText();
        String redisKey = REDIS_KEY_PREFIX;

        // 存储验证码到 Redis，有效期为 5 分钟
        redisTemplate.opsForValue().set(redisKey, captchaText, 5, TimeUnit.MINUTES);

        // 生成验证码图片
        BufferedImage image = kaptchaProducer.createImage(captchaText);

        // 设置响应头
        response.setContentType("image/jpeg");
        try {
            ImageIO.write(image, "jpeg", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 用户登录逻辑
     */
    @Override
    public Response<Map<String, Object>> login(String email, String password, String code) {
        String redisKey = REDIS_KEY_PREFIX;

        // 从 Redis 获取验证码
        String sessionCode = redisTemplate.opsForValue().get(redisKey);
        if (sessionCode == null || !sessionCode.equalsIgnoreCase(code)) {
            // 验证码错误或过期时，删除 Redis 中的验证码（防止暴力破解）
            redisTemplate.delete(redisKey);
            return new Response<>(400, "验证码错误或已过期", null);
        }

        // 验证用户信息
        Admin admin = adminMapper.selectByEmail(email);
        if (admin == null) {
            return new Response<>(404, "用户不存在", null);
        }

//        // 验证密码
//        if (!BCrypt.checkpw(password, admin.getPassword())) {
//            return new Response<>(402, "密码错误", null);
//        }
        // 验证密码
        if (password.equals(admin.getPassword())) {
            return new Response<>(402, "密码错误", null);
        }

        // 清除 Redis 中的验证码（成功验证后）
        redisTemplate.delete(redisKey);

        // 使用 Sa-Token 生成登录会话
        StpUtil.login(admin.getId());

        // 获取 Token 信息
        String token = StpUtil.getTokenValue();

        // 构造返回数据
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("satoken", token);
        responseData.put("id", admin.getId());
        responseData.put("name", admin.getUsername());

        // 返回登录成功信息
        return new Response<>(200, "登录成功", responseData);
    }
}
